<template>
  <div class="container">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="15" animated />
      <div class="loading-tip">加载问题详情中，请稍候...</div>
    </div>
    
    <div v-else-if="!question" class="not-found">
      <el-empty description="问题不存在或已删除">
        <template #description>
          <p>该问题可能已被删除或您没有权限查看</p>
        </template>
        <el-button type="primary" @click="$router.push('/questions')">返回问题列表</el-button>
      </el-empty>
    </div>
    
    <div v-else class="question-detail">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/questions' }">问题列表</el-breadcrumb-item>
          <el-breadcrumb-item>问题详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      
      <!-- 回到顶部按钮 -->
      <div class="back-to-top" :class="{ 'show': showBackToTop }" @click="scrollToTop">
        <i class="el-icon-top"></i>
      </div>
      
      <!-- 问题卡片 -->
      <div class="question-card" :class="{'solved-question': question.status === 2}">
        <!-- 问题标题 -->
        <h1 class="question-title">{{ question.title }}</h1>
        
        <!-- 问题状态 -->
        <div class="question-status">
          <el-tag 
            :type="getQuestionStatusType(question.status)" 
            effect="light" 
            size="small"
          >
            {{ getQuestionStatusText(question.status) }}
          </el-tag>
        </div>
        
        <!-- 问题元信息 -->
        <div class="question-meta">
          <div class="author-info">
            <el-avatar :size="36" :src="question.avatar"></el-avatar>
            <div class="user-info">
              <div class="username">{{ question.nickname }}</div>
              <div class="publish-time">发布于 {{ formatTime(question.createTime) }}</div>
            </div>
          </div>
          
          <div class="question-stats">
            <span class="stat-item">
              <i class="el-icon-view"></i>
              {{ question.viewCount || 0 }} 浏览
            </span>
            <span class="stat-item">
              <i class="el-icon-chat-line-square"></i>
              {{ question.answerCount || 0 }} 回答
            </span>
          </div>
        </div>
        
        <!-- 问题标签 -->
        <div class="question-tags" v-if="questionTags.length > 0">
          <el-tag
            v-for="tag in questionTags"
            :key="tag"
            size="small"
            effect="plain"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
        </div>
        
        <!-- 问题内容 -->
        <div class="question-content">
          <div v-if="question.content.length > 300 && !showFullContent" class="collapsed-content">
            <div v-html="formatContentPreview(question.content)"></div>
            <div class="expand-btn" @click="showFullContent = true">
              <el-button type="text">
                显示全部 <i class="el-icon-arrow-down"></i>
              </el-button>
            </div>
          </div>
          <div v-else class="markdown-content" v-html="question.content"></div>
        </div>
        
        <!-- 问题操作 -->
        <div class="question-actions">
          <ShareButton 
            :target-type="1" 
            :target-id="question.id" 
            size="small" 
          />
          <div class="action-buttons">
            <!-- 收藏 -->
            <el-button
              type="text"
              class="action-btn"
              :class="{'is-active': isCollected}"
              @click="isLogin ? toggleCollect() : showLoginTip('收藏')"
            >
              <i :class="isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
              <span>{{ isCollected ? '已收藏' : '收藏' }}</span>
              <span v-if="questionStats && questionStats.collectCount > 0" class="count-badge">{{ questionStats.collectCount }}</span>
            </el-button>
            
            <!-- 关注 -->
            <el-button
              type="text"
              class="action-btn"
              :class="{'is-active': isFollowed}"
              @click="isLogin ? toggleFollow() : showLoginTip('关注')"
            >
              <i :class="isFollowed ? 'el-icon-check' : 'el-icon-plus'"></i>
              <span>{{ isFollowed ? '已关注' : '关注' }}</span>
              <span v-if="questionStats && questionStats.followCount > 0" class="count-badge">{{ questionStats.followCount }}</span>
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 回答区域 -->
      <div class="answers-section">
        <div class="answers-header">
          <h2 class="answers-title">{{ answerList.length }} 个回答</h2>
          <div class="sort-options">
            <el-radio-group v-model="sortType" size="small">
              <el-radio-button label="default">默认</el-radio-button>
              <el-radio-button label="time">最新</el-radio-button>
              <el-radio-button label="votes">热门</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <!-- 回答列表 -->
        <transition-group name="list" tag="div" class="answer-list">
          <div
            v-for="(answer, index) in sortedAnswers"
            :key="answer.id"
            :class="['answer-card', {'best-answer': answer.isAccepted}]"
          >
            <!-- 回答元信息 -->
            <div class="answer-meta">
              <div class="author-info">
                <div class="avatar">
                  <el-avatar :src="answer.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" :size="40"></el-avatar>
                </div>
                <div class="info">
                  <div class="username">{{ answer.nickname || answer.username }}</div>
                  <div class="answer-meta">
                    <span class="time">{{ formatTime(answer.createTime) }}</span>
                    <span v-if="answer.isAccepted" class="accepted-tag">
                      <i class="el-icon-check"></i> 已采纳
                    </span>
                  </div>
                </div>
              </div>
              
              <!-- 最佳答案标签 -->
              <div v-if="answer.isAccepted" class="best-answer-badge">
                <el-tag type="success">最佳答案</el-tag>
              </div>
            </div>
            
            <!-- 回答内容 -->
            <div class="answer-content">
              <div v-if="answer.content.length > 300 && !expandedAnswers.includes(answer.id)" class="content-preview">
                <div v-html="formatContentPreview(answer.content)"></div>
                <div class="show-more" @click="expandAnswer(answer.id)">
                  <span>显示全部</span>
                  <i class="el-icon-arrow-down"></i>
                </div>
              </div>
              <div v-else class="content-full markdown-content" v-html="answer.content"></div>
            </div>
            
            <!-- 用户回复信息，处理@null问题 -->
            <div v-if="answer.replyToUser" class="user-reply">
              <div class="reply-header">
                <div class="reply-author">
                  回复 {{ answer.replyToUsername || '用户' }}
                </div>
              </div>
              <div class="reply-content">
                {{ answer.replyContent || '' }}
              </div>
            </div>
            
            <!-- 回答操作 -->
            <div class="answer-actions">
              <AnswerActions 
                :answer="answer"
                :isLogin="isLogin"
                :isQuestionAuthor="isQuestionAuthor"
                :questionStatus="question.status"
                :activeCommentId="activeCommentId"
                :handleVote="handleVote"
                :showComments="showComments"
                :showLoginTip="showLoginTip"
                :confirmAcceptAnswer="confirmAcceptAnswer"
              />
            </div>
            
            <!-- 评论区域（默认隐藏，点击评论按钮显示） -->
            <transition name="comments">
              <div v-if="activeCommentId === answer.id" class="comments-section">
                <CommentList 
                  :answerId="answer.id" 
                  @update:count="updateCommentCount(answer.id, $event)"
                />
              </div>
            </transition>
          </div>
        </transition-group>
        
        <div v-if="!answerList.length" class="no-answers">
          <el-empty description="暂无回答">
            <template #description>
              <p>该问题还没有人回答，成为第一个回答的人吧！</p>
            </template>
          </el-empty>
        </div>
      </div>
      
      <!-- 我要回答 -->
      <div class="add-answer-section">
        <h3 class="section-title">撰写回答</h3>
        
        <div v-if="!isLogin" class="login-to-answer">
          <p>登录后才能回答问题</p>
          <el-button type="primary" @click="$router.push('/login')">立即登录</el-button>
        </div>
        
        <div v-else-if="question.status !== 1" class="closed-hint">
          <p>该问题已{{ question.status === 2 ? '解决' : '关闭' }}，无法添加新回答</p>
        </div>
        
        <div v-else class="answer-editor">
          <el-form :model="answerForm" @submit.prevent="submitAnswer">
            <el-form-item>
              <!-- 使用统一的Markdown编辑器组件 -->
              <MarkdownEditor
                v-if="mdEditorLoaded"
                v-model="answerForm.content"
                height="300px"
                placeholder="请输入您的回答..."
                :theme="editorTheme"
                @change="() => {}"
              />
              
              <!-- 使用文本域作为备选 -->
              <template v-else>
                <div class="editor-toolbar">
                  <div class="toolbar-btn" @click="formatText('bold')" title="加粗">
                    <i class="el-icon-bold"></i>
                  </div>
                  <div class="toolbar-btn" @click="formatText('italic')" title="斜体">
                    <i class="el-icon-italic"></i>
                  </div>
                  <div class="toolbar-btn" @click="formatText('underline')" title="下划线">
                    <i class="el-icon-underline"></i>
                  </div>
                  <div class="toolbar-btn" @click="insertLink()" title="插入链接">
                    <i class="el-icon-link"></i>
                  </div>
                  <div class="toolbar-btn" @click="insertImage()" title="插入图片">
                    <i class="el-icon-picture"></i>
                  </div>
                </div>
                <el-input
                  v-model="answerForm.content"
                  type="textarea"
                  :rows="8"
                  placeholder="请输入您的回答..."
                  :maxlength="10000"
                  show-word-limit
                ></el-input>
              </template>
            </el-form-item>
            
            <el-form-item>
              <div class="answer-submit">
                <div class="answer-tips">
                  <el-alert
                    type="info"
                    :closable="false"
                    show-icon
                  >
                    <template #title>
                      <span class="tips-title">提示：</span>
                      <ul class="tips-list">
                        <li>详细、有条理的回答更容易被采纳</li>
                        <li>可使用Markdown语法编写专业回答</li>
                      </ul>
                    </template>
                  </el-alert>
                </div>
                <el-button 
                  type="primary" 
                  :loading="submitting"
                  @click="submitAnswer"
                  :disabled="!answerForm.content.trim()"
                >提交回答</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 相关问题 -->
      <div class="related-questions" v-if="relatedQuestions.length > 0">
        <h3 class="section-title">相关问题</h3>
        <ul class="related-list">
          <li v-for="(rq, index) in relatedQuestions" :key="index" class="related-item">
            <router-link :to="`/question/${rq.id}`" class="related-link">
              {{ rq.title }}
            </router-link>
            <span class="answer-count">{{ rq.answerCount || 0 }}个回答</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useQuestionStore } from '../stores/question'
import ShareButton from '../components/ShareButton.vue'
import CommentList from '../components/CommentList.vue'
import AnswerActions from '../components/AnswerActions.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { collectQuestion, cancelCollect, checkCollected } from '../api/collection'
import { voteAnswer, cancelVote, checkVoteStatus } from '../api/vote'
import { getAnswerList, createAnswer, acceptAnswer } from '../api/answer'
import MarkdownEditor from '../components/MarkdownEditor.vue'

export default {
  name: 'QuestionDetailPage',
  components: {
    ShareButton,
    CommentList,
    AnswerActions,
    MarkdownEditor
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    const questionStore = useQuestionStore()
    
    const loading = ref(true)
    const question = computed(() => questionStore.questionDetail)
    const isLogin = computed(() => userStore.isLogin)
    const currentUser = computed(() => userStore.userInfo)
    const answerList = ref([])
    
    // 问题统计信息
    const questionStats = ref({
      collectCount: 0,
      followCount: 0
    })
    
    // 是否是问题作者
    const isQuestionAuthor = computed(() => {
      if (!isLogin.value || !question.value) return false
      return currentUser.value.id === question.value.userId
    })
    
    // 排序方式
    const sortType = ref('default')
    const sortedAnswers = computed(() => {
      if (!answerList.value) return []
      
      const answers = [...answerList.value]
      
      if (sortType.value === 'time') {
        return answers.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
      } else if (sortType.value === 'votes') {
        return answers.sort((a, b) => (b.voteCount || 0) - (a.voteCount || 0))
      } else {
        // 默认排序：采纳答案置顶，其余按点赞数
        return answers.sort((a, b) => {
          if (a.isAccepted && !b.isAccepted) return -1
          if (!a.isAccepted && b.isAccepted) return 1
          return (b.voteCount || 0) - (a.voteCount || 0)
        })
      }
    })
    
    // 评论相关
    const activeCommentId = ref(null)
    
    // 标签处理
    const questionTags = computed(() => {
      if (!question.value || !question.value.tags) return []
      return question.value.tags.split(',').filter(tag => tag.trim())
    })
    
    // 收藏和关注
    const isCollected = ref(false)
    const isFollowed = ref(false)
    
    // 回答表单
    const answerForm = ref({ content: '' })
    const submitting = ref(false)
    const mdEditorLoaded = ref(false)
    
    // 编辑器主题
    const editorTheme = ref('light')
    
    // 相关问题
    const relatedQuestions = ref([])
    
    // 内容折叠相关
    const showFullContent = ref(false)
    const expandedAnswers = ref([])
    
    // 回到顶部按钮
    const showBackToTop = ref(false)
    
    // 加载问题详情
    const fetchQuestionDetail = async () => {
      loading.value = true
      try {
        const id = route.params.id
        await questionStore.fetchQuestionDetail(id)
        
        // 加载回答列表
        await loadAnswers()
        
        // 检查收藏状态
        if (isLogin.value) {
          try {
            const res = await checkCollected(1, id)
            isCollected.value = res.data
          } catch (err) {
            console.error('获取收藏状态失败:', err)
          }
        }
        
        // 延迟加载编辑器
        nextTick(() => {
          setTimeout(() => {
            mdEditorLoaded.value = true
          }, 500) // 延迟500ms确保组件正确加载
        })
      } catch (error) {
        console.error('获取问题详情失败:', error)
        ElMessage.error('获取问题详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 加载回答列表
    const loadAnswers = async () => {
      try {
        const questionId = route.params.id
        const res = await getAnswerList(questionId, { current: 1, size: 100 })
        answerList.value = res.data.records || []
        
        // 获取当前用户对各回答的点赞状态
        if (isLogin.value) {
          await Promise.all(answerList.value.map(async (answer) => {
            try {
              const voteRes = await checkVoteStatus(answer.id)
              answer.voteStatus = voteRes.data
            } catch (err) {
              console.error('获取点赞状态失败:', err)
            }
          }))
        }
      } catch (error) {
        console.error('获取回答列表失败:', error)
      }
    }
    
    // 格式化时间
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      
      const now = new Date()
      const date = new Date(timestamp)
      const diff = Math.floor((now - date) / 1000) // 时间差（秒）
      
      if (diff < 60) {
        return `${diff}秒前`
      } else if (diff < 3600) {
        return `${Math.floor(diff / 60)}分钟前`
      } else if (diff < 86400) {
        return `${Math.floor(diff / 3600)}小时前`
      } else if (diff < 604800) {
        return `${Math.floor(diff / 86400)}天前`
      } else {
        return date.toLocaleDateString()
      }
    }
    
    // 收藏问题
    const toggleCollect = async () => {
      try {
        if (isCollected.value) {
          await cancelCollect(question.value.id)
          isCollected.value = false
          ElMessage.success('已取消收藏')
        } else {
          await collectQuestion(question.value.id)
          isCollected.value = true
          ElMessage.success('收藏成功')
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    // 关注问题
    const toggleFollow = () => {
      // TODO: 实现关注功能
      ElMessage.info('关注功能开发中')
    }
    
    // 显示登录提示
    const showLoginTip = (action) => {
      ElMessageBox.confirm(
        `您需要登录后才能${action}，是否前往登录？`,
        '提示',
        {
          confirmButtonText: '去登录',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        router.push('/login')
      }).catch(() => {})
    }
    
    // 确认采纳回答
    const confirmAcceptAnswer = (answerId) => {
      ElMessageBox.confirm(
        '采纳后将不能更改，确认采纳该回答为最佳答案吗？',
        '确认采纳',
        {
          confirmButtonText: '确认采纳',
          cancelButtonText: '取消',
          type: 'success'
        }
      ).then(() => {
        acceptAnswerHandler(answerId)
      }).catch(() => {})
    }
    
    // 获取问题状态类型
    const getQuestionStatusType = (status) => {
      const types = {
        0: 'info',    // 待审核
        1: 'primary', // 已发布
        2: 'success', // 已解决
        3: 'warning'  // 已关闭
      }
      return types[status] || 'info'
    }
    
    // 获取问题状态文本
    const getQuestionStatusText = (status) => {
      const texts = {
        0: '待审核',
        1: '进行中',
        2: '已解决',
        3: '已关闭'
      }
      return texts[status] || '未知状态'
    }
    
    // 投票操作优化
    const handleVote = async (answerId, voteType) => {
      if (!isLogin.value) {
        router.push('/login')
        return
      }
      
      try {
        // 获取当前回答
        const answer = answerList.value.find(item => item.id === answerId)
        if (!answer) return
        
        // 如果已经投了同类型的票，则取消
        if ((voteType === 'up' && answer.voteStatus === 1) || 
            (voteType === 'down' && answer.voteStatus === 2)) {
          await cancelVote(answerId)
          // 乐观更新UI
          answer.voteStatus = 0
          if (voteType === 'up') answer.voteCount--
          else if (voteType === 'down') answer.voteCount++
          
          ElMessage.success('已取消投票')
        } else {
          // 投新票
          await voteAnswer({
            answerId: answerId,
            voteType: voteType === 'up' ? 1 : 2 
          })
          
          // 乐观更新UI
          const oldStatus = answer.voteStatus
          answer.voteStatus = voteType === 'up' ? 1 : 2
          
          // 更新票数
          if (oldStatus === 0) {
            // 之前没投票
            if (voteType === 'up') answer.voteCount++
            else if (voteType === 'down') answer.voteCount--
          } else {
            // 之前投的是相反的票
            if (voteType === 'up') answer.voteCount += 2
            else if (voteType === 'down') answer.voteCount -= 2
          }
          
          ElMessage.success(voteType === 'up' ? '点赞成功' : '已踩')
        }
      } catch (error) {
        console.error('投票操作失败:', error)
        ElMessage.error('操作失败，请稍后重试')
        // 失败后重新加载
        await loadAnswers()
      }
    }
    
    // 显示/隐藏评论
    const showComments = async (answerId) => {
      if (activeCommentId.value === answerId) {
        activeCommentId.value = null
      } else {
        activeCommentId.value = answerId
      }
    }
    
    // 更新评论数量
    const updateCommentCount = (answerId, count) => {
      const answerIndex = answerList.value.findIndex(a => a.id === answerId)
      if (answerIndex !== -1) {
        // 确保计数是数字并且不小于0
        answerList.value[answerIndex].commentCount = Math.max(0, parseInt(count, 10) || 0)
      }
    }
    
    // 采纳回答
    const acceptAnswerHandler = async (answerId) => {
      try {
        await acceptAnswer(answerId)
        ElMessage.success('已采纳该回答')
        
        // 重新加载回答列表
        await loadAnswers()
      } catch (error) {
        console.error('采纳回答失败:', error)
        ElMessage.error('采纳回答失败')
      }
    }
    
    // 提交回答
    const submitAnswer = async () => {
      if (!isLogin.value) {
        router.push('/login')
        return
      }
      
      if (!answerForm.value.content.trim()) {
        ElMessage.warning('回答内容不能为空')
        return
      }
      
      submitting.value = true
      try {
        await createAnswer({
          questionId: question.value.id,
          content: answerForm.value.content
        })
        
        ElMessage.success('回答提交成功')
        answerForm.value.content = ''
        
        // 重新加载回答列表
        await loadAnswers()
      } catch (error) {
        console.error('提交回答失败:', error)
        ElMessage.error('提交回答失败')
      } finally {
        submitting.value = false
      }
    }
    
    // 展开回答
    const expandAnswer = (answerId) => {
      expandedAnswers.value.push(answerId)
    }
    
    // 格式化内容预览 - 支持Markdown渲染
    const formatContentPreview = (content) => {
      const maxLength = 300
      if (content.length <= maxLength) return content
      
      // 截取内容并保留HTML标签
      let preview = content.substring(0, maxLength) + '...'
      return preview
    }
    
    // 富文本编辑功能
    const formatText = (type) => {
      const textarea = document.querySelector('.answer-editor textarea')
      if (!textarea) return
      
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      const selectedText = answerForm.value.content.substring(start, end)
      
      let formattedText = ''
      switch (type) {
        case 'bold':
          formattedText = `**${selectedText}**`
          break
        case 'italic':
          formattedText = `*${selectedText}*`
          break
        case 'underline':
          formattedText = `<u>${selectedText}</u>`
          break
        default:
          formattedText = selectedText
      }
      
      // 替换选中文本
      answerForm.value.content = 
        answerForm.value.content.substring(0, start) + 
        formattedText + 
        answerForm.value.content.substring(end)
      
      // 聚焦回文本框
      nextTick(() => {
        textarea.focus()
        textarea.setSelectionRange(start, start + formattedText.length)
      })
    }
    
    // 插入链接
    const insertLink = () => {
      ElMessageBox.prompt('请输入链接地址', '插入链接', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: 'https://'
      }).then(({ value }) => {
        if (!value) return
        
        const textarea = document.querySelector('.answer-editor textarea')
        if (!textarea) return
        
        const start = textarea.selectionStart
        const end = textarea.selectionEnd
        const selectedText = answerForm.value.content.substring(start, end)
        
        const linkText = selectedText || '链接文本'
        const markdown = `[${linkText}](${value})`
        
        // 替换选中文本
        answerForm.value.content = 
          answerForm.value.content.substring(0, start) + 
          markdown + 
          answerForm.value.content.substring(end)
        
        // 聚焦回文本框
        nextTick(() => {
          textarea.focus()
        })
      }).catch(() => {})
    }
    
    // 插入图片
    const insertImage = () => {
      ElMessageBox.prompt('请输入图片地址', '插入图片', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: 'https://'
      }).then(({ value }) => {
        if (!value) return
        
        const textarea = document.querySelector('.answer-editor textarea')
        if (!textarea) return
        
        const start = textarea.selectionStart
        const markdown = `![图片](${value})`
        
        // 插入图片markdown
        answerForm.value.content = 
          answerForm.value.content.substring(0, start) + 
          markdown + 
          answerForm.value.content.substring(start)
        
        // 聚焦回文本框
        nextTick(() => {
          textarea.focus()
        })
      }).catch(() => {})
    }
    
    // 滚动到顶部
    const scrollToTop = () => {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
    
    // 监听滚动事件，控制回到顶部按钮显示
    onMounted(() => {
      window.addEventListener('scroll', handleScroll)
      fetchQuestionDetail()
    })
    
    // 组件销毁时移除事件监听
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll)
    })
    
    // 处理滚动事件
    const handleScroll = () => {
      if (window.scrollY > 300) {
        showBackToTop.value = true
      } else {
        showBackToTop.value = false
      }
    }
    
    return {
      loading,
      question,
      isLogin,
      isQuestionAuthor,
      sortType,
      sortedAnswers,
      activeCommentId,
      questionTags,
      isCollected,
      isFollowed,
      answerForm,
      submitting,
      relatedQuestions,
      answerList,
      mdEditorLoaded,
      editorTheme,
      formatTime,
      toggleCollect,
      toggleFollow,
      getQuestionStatusType,
      getQuestionStatusText,
      handleVote,
      showComments,
      updateCommentCount,
      acceptAnswer: acceptAnswerHandler,
      submitAnswer,
      showFullContent,
      expandedAnswers,
      expandAnswer,
      formatContentPreview,
      formatText,
      insertLink,
      insertImage,
      showLoginTip,
      confirmAcceptAnswer,
      showBackToTop,
      scrollToTop
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 24px auto;
  padding: 0 16px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 8px 0;
}

.loading-container {
  padding: 24px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.not-found {
  background-color: white;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 问题卡片 */
.question-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 28px;
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.question-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0 0 20px;
  line-height: 1.4;
}

.question-status {
  margin-bottom: 16px;
}

.question-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.author-info {
  display: flex;
  align-items: center;
}

.user-info {
  margin-left: 12px;
}

.username {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.publish-time {
  color: #8c8c8c;
  font-size: 13px;
  margin-top: 2px;
}

.question-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #8c8c8c;
  font-size: 14px;
}

.question-tags {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  border-radius: 16px;
  padding: 2px 10px;
  background-color: #f4f8fd;
}

.question-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 28px;
  word-break: break-word;
  white-space: pre-wrap;
  text-align: left;
}

.question-content :deep(p), .answer-content :deep(p) {
  margin-bottom: 16px;
}

.question-content :deep(img), .answer-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 12px 0;
}

.question-content :deep(a), .answer-content :deep(a) {
  color: var(--color-primary);
  text-decoration: none;
}

.question-content :deep(pre), .answer-content :deep(pre) {
  background-color: #f6f8fa;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
}

.collapsed-content {
  position: relative;
}

.expand-btn {
  text-align: center;
  margin-top: 12px;
  padding-top: 24px;
  position: relative;
}

.expand-btn::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 60px;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
}

.question-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  transition: all 0.2s ease;
}

.action-btn:hover, .action-btn.is-active {
  color: var(--color-primary);
  background-color: #f0f7ff;
  border-radius: 4px;
}

/* 回答区域 */
.answers-section {
  margin-bottom: 40px;
}

.answers-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 12px;
}

.answers-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  position: relative;
  padding-left: 12px;
}

.answers-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: var(--color-primary);
  border-radius: 2px;
}

.answer-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.best-answer {
  border-left: 4px solid var(--color-success);
  background-color: #f0fdf4;
}

.answer-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.best-answer-badge {
  margin-left: auto;
}

.answer-content {
  font-size: 15px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 20px;
  word-break: break-word;
  white-space: pre-wrap;
  text-align: left;
}

.answer-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 20px;
}

.vote-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f5f5f5;
  padding: 4px 12px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.vote-count {
  font-size: 16px;
  font-weight: 600;
  min-width: 32px;
  text-align: center;
  color: #333;
}

.other-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.voted {
  background-color: #e6f7ff;
  color: var(--color-primary);
}

/* 评论区域 */
.comments-section {
  margin-top: 12px;
  border-top: 1px dashed #e0e0e0;
  padding-top: 12px;
}

/* 评论区域动画 */
.comments-enter-active,
.comments-leave-active {
  transition: all 0.3s ease;
  max-height: 1000px;
  overflow: hidden;
}

.comments-enter-from,
.comments-leave-to {
  max-height: 0;
  opacity: 0;
}

/* 添加回答区域 */
.add-answer-section {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 28px;
  margin-bottom: 28px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px;
  position: relative;
  padding-left: 12px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: var(--color-primary);
  border-radius: 2px;
}

.login-to-answer {
  text-align: center;
  padding: 32px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.closed-hint {
  text-align: center;
  padding: 32px;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #8c8c8c;
}

.answer-editor :deep(.el-textarea__inner) {
  padding: 16px;
  line-height: 1.8;
  font-size: 15px;
  border-radius: 0 0 4px 4px;
  resize: vertical;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

/* 相关问题 */
.related-questions {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 28px;
}

.related-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.related-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.related-item:last-child {
  border-bottom: none;
}

.related-link {
  color: #333;
  text-decoration: none;
  flex: 1;
  margin-right: 16px;
  font-size: 15px;
  line-height: 1.6;
  transition: color 0.2s ease;
}

.related-link:hover {
  color: var(--color-primary);
}

.answer-count {
  color: #8c8c8c;
  font-size: 13px;
  background-color: #f5f5f5;
  padding: 2px 8px;
  border-radius: 12px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding: 0 12px;
    margin: 16px auto;
  }
  
  .question-card,
  .answer-card,
  .add-answer-section,
  .related-questions {
    padding: 20px;
    border-radius: 8px;
  }
  
  .question-title {
    font-size: 20px;
  }
  
  .question-meta,
  .answer-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .question-stats {
    width: 100%;
    justify-content: flex-start;
  }
  
  .answer-actions {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .other-actions {
    width: 100%;
    justify-content: space-between;
  }
}

/* 排序选项 */
.sort-options {
  display: flex;
  align-items: center;
}

/* 列表动画 */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 动画效果 */
.question-card:hover,
.answer-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.vote-buttons {
  transition: all 0.3s ease;
}

.vote-buttons:hover {
  background-color: #e0e0e0;
}

/* 回到顶部按钮 */
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background-color: var(--color-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  opacity: 0;
}

.back-to-top.show {
  opacity: 1;
}

.back-to-top i {
  color: white;
  font-size: 20px;
}

/* 自定义富文本编辑器样式已迁移到MarkdownEditor组件 */

/* 保留简单编辑器样式用于备选 */
.editor-toolbar {
  display: flex;
  padding: 8px;
  background-color: #f5f5f5;
  border: 1px solid #dcdfe6;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
}

.toolbar-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-right: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.toolbar-btn:hover {
  background-color: #e6e6e6;
}

.answer-submit {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-top: 16px;
}

.answer-tips {
  flex: 1;
  margin-right: 16px;
}

.tips-title {
  font-weight: 600;
}

.tips-list {
  padding-left: 20px;
  margin: 4px 0 0;
}

.tips-list li {
  font-size: 12px;
  margin-bottom: 4px;
  color: #606266;
}

.comment-btn {
  position: relative;
  display: flex;
  align-items: center;
  gap: 4px;
}

.comment-count {
  color: #909399;
  font-weight: normal;
}

/* 投票按钮样式 */
.vote-buttons {
  display: flex;
  align-items: center;
  gap: 5px;
}

.vote-btn {
  transition: all 0.2s ease;
}

.vote-count {
  font-size: 16px;
  font-weight: 600;
  min-width: 30px;
  text-align: center;
}

.voted-up {
  color: #409EFF;
}

.voted-down {
  color: #F56C6C;
}

/* @null 显示修复 */
.user-reply {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 10px;
}

.user-reply .reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.user-reply .reply-author {
  font-weight: bold;
}

.user-reply .reply-content {
  color: #333;
}
</style> 